<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="30%"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-width="70px" :rules="rules">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch } from 'vue'
import { addAdmin, editAdmin } from '@/api/admin'
import i18n from '@/i18n'
import { SHA256 } from '@/api/sha256.js'
import { ElMessage } from 'element-plus'
const props = defineProps({
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogTableValue: {
    type: Object,
    default: () => {}
  }
})

const formRef = ref(null)
const form = ref({
  name: '',
  account: '',
  password: ''
})
const emits = defineEmits(['update:modelValue', 'initUserList'])

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = async () => {
  form.value.password = SHA256(form.value.password)
  props.dialogTitle === '添加管理员'
    ? await addAdmin(form.value)
    : await editAdmin(form.value)
  ElMessage({
    message: i18n.global.t('操作成功'),
    type: 'success'
  })
  emits('initUserList')
  handleClose()
}
const rules = ref({
  name: [{ required: true, message: 'Please input username', trigger: 'blur' }],
  password: [
    { required: true, message: 'Please input password', trigger: 'blur' }
  ],
  account: [{ required: true, message: 'Please input mobile', trigger: 'blur' }]
})

watch(
  () => props.dialogTableValue,
  () => {
    form.value = props.dialogTableValue
  },
  { deep: true, immediate: true }
)
</script>

<style></style>